package com.liyuxiang.graph.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * AI响应缓存服务 - 优化重复查询的响应速度
 */
@Service
public class AiCacheService {
    
    private static final Logger logger = LoggerFactory.getLogger(AiCacheService.class);
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    private static final String INTENT_CACHE_PREFIX = "ai:intent:";
    private static final String CONVERSATION_CACHE_PREFIX = "ai:conversation:";
    private static final long DEFAULT_TTL_MINUTES = 30; // 缓存30分钟
    
    /**
     * 获取意图识别缓存 - 支持上下文感知
     */
    public <T> T getIntentCache(String query, String userId, String conversationContext, Class<T> clazz) {
        try {
            String cacheKey = generateIntentCacheKey(query, userId, conversationContext);
            String cached = redisTemplate.opsForValue().get(cacheKey);
            if (cached != null) {
                logger.info("意图识别缓存命中 - 用户ID: {}, 查询: {}", userId, query);
                return objectMapper.readValue(cached, clazz);
            }
        } catch (Exception e) {
            logger.warn("获取意图识别缓存失败: {}", e.getMessage());
        }
        return null;
    }
    
    // 兼容旧版本
    public <T> T getIntentCache(String query, String userId, Class<T> clazz) {
        return getIntentCache(query, userId, "", clazz);
    }
    
    /**
     * 设置意图识别缓存 - 支持上下文感知
     */
    public void setIntentCache(String query, String userId, String conversationContext, Object result) {
        try {
            String cacheKey = generateIntentCacheKey(query, userId, conversationContext);
            String json = objectMapper.writeValueAsString(result);
            redisTemplate.opsForValue().set(cacheKey, json, Duration.ofMinutes(DEFAULT_TTL_MINUTES));
            logger.info("意图识别缓存已设置 - 用户ID: {}, 查询: {}", userId, query);
        } catch (Exception e) {
            logger.warn("设置意图识别缓存失败: {}", e.getMessage());
        }
    }
    
    // 兼容旧版本
    public void setIntentCache(String query, String userId, Object result) {
        setIntentCache(query, userId, "", result);
    }
    
    /**
     * 获取对话处理缓存 - 支持对话阶段区分
     */
    public <T> T getConversationCache(String query, String userId, String conversationStage, Class<T> clazz) {
        try {
            String cacheKey = generateConversationCacheKey(query, userId, conversationStage);
            String cached = redisTemplate.opsForValue().get(cacheKey);
            if (cached != null) {
                logger.info("对话处理缓存命中 - 用户ID: {}, 查询: {}", userId, query);
                return objectMapper.readValue(cached, clazz);
            }
        } catch (Exception e) {
            logger.warn("获取对话处理缓存失败: {}", e.getMessage());
        }
        return null;
    }
    
    // 兼容旧版本
    public <T> T getConversationCache(String query, String userId, Class<T> clazz) {
        return getConversationCache(query, userId, "", clazz);
    }
    
    /**
     * 设置对话处理缓存 - 支持对话阶段区分
     */
    public void setConversationCache(String query, String userId, String conversationStage, Object result) {
        try {
            String cacheKey = generateConversationCacheKey(query, userId, conversationStage);
            String json = objectMapper.writeValueAsString(result);
            redisTemplate.opsForValue().set(cacheKey, json, Duration.ofMinutes(DEFAULT_TTL_MINUTES));
            logger.info("对话处理缓存已设置 - 用户ID: {}, 查询: {}", userId, query);
        } catch (Exception e) {
            logger.warn("设置对话处理缓存失败: {}", e.getMessage());
        }
    }
    
    // 兼容旧版本
    public void setConversationCache(String query, String userId, Object result) {
        setConversationCache(query, userId, "", result);
    }
    
    /**
     * 清理所有相关缓存
     */
    public void clearUserCache(String userId) {
        try {
            // 清理意图识别缓存
            String intentPattern = INTENT_CACHE_PREFIX + userId + ":*";
            redisTemplate.delete(redisTemplate.keys(intentPattern));
            
            // 清理对话处理缓存
            String conversationPattern = CONVERSATION_CACHE_PREFIX + userId + ":*";
            redisTemplate.delete(redisTemplate.keys(conversationPattern));
            
            logger.info("已清理用户缓存 - 用户ID: {}", userId);
        } catch (Exception e) {
            logger.warn("清理用户缓存失败 - 用户ID: {}, 错误: {}", userId, e.getMessage());
        }
    }
    
    /**
     * 生成意图识别缓存key - 包含对话上下文
     */
    public String generateIntentCacheKey(String query, String userId, String conversationContext) {
        // 结合查询内容和对话上下文生成更精准的缓存key
        String contextHash = String.valueOf((query + conversationContext).hashCode());
        return INTENT_CACHE_PREFIX + userId + ":" + contextHash;
    }
    
    /**
     * 生成对话处理缓存key - 包含对话阶段
     */
    public String generateConversationCacheKey(String query, String userId, String conversationStage) {
        String stageHash = String.valueOf((query + conversationStage).hashCode());
        return CONVERSATION_CACHE_PREFIX + userId + ":" + stageHash;
    }
    
    // 兼容旧版本的方法
    private String generateIntentCacheKey(String query, String userId) {
        return generateIntentCacheKey(query, userId, "");
    }
    
    private String generateConversationCacheKey(String query, String userId) {
        return generateConversationCacheKey(query, userId, "");
    }
}